package com.apabi.service.email.impl;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.apabi.common.config.Global;
import com.apabi.mapper.SysUserMapper;
import com.apabi.pojo.SysUser;
import com.apabi.service.email.EmailService;

import freemarker.template.Template;

public class EmailServiceImpl implements EmailService {  
	
	@Autowired
	private SysUserMapper sysUserMapper;
	
	final static Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);
	
    private JavaMailSender mailSender;  
    private FreeMarkerConfigurer freeMarkerConfigurer;   
    private static final String ENCODING = "utf-8";  
  
    public void setMailSender(JavaMailSender mailSender) {  
        this.mailSender = mailSender;  
    }  
  
    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {  
        this.freeMarkerConfigurer = freeMarkerConfigurer;  
    }  
      
  
    /** 
     * 发送带附件的html格式邮件 
     * type
     */  
    public void sendEmail(String type,SysUser sysUser) {  
        MimeMessage msg = null;  
        try {
            msg = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, ENCODING);  
            helper.setFrom(Global.getConfig("email.username"));  //解决名字乱码问题使用：MimeUtility.encodeText(name, "UTF-8", "B")
            helper.setTo(sysUser.getUsername()); 
            if(Global.EMAIL_RESET.equals(type)){
            	helper.setSubject(MimeUtility.encodeText("重置密码", ENCODING, "B"));  
            }else{
            	helper.setSubject(MimeUtility.encodeText("激活邮件", ENCODING, "B"));  
            }
            helper.setText(getMailText(type,sysUser), true); // true表示text的内容为html  
              
            // 添加内嵌文件，第1个参数为cid标识这个文件,第2个参数为资源  
            //helper.addInline("welcomePic", new File("d:/welcome.gif")); // 附件内容  
              
            // 这里的方法调用和插入图片是不同的，解决附件名称的中文问题  
           // File file = new File("d:/欢迎注册.docx");  
           // helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);  
        } catch (Exception e) {  
            throw new RuntimeException("error happens", e);  
        }   
        mailSender.send(msg); 
    	log.debug("邮件发送成功...");
    }  
  
    /** 
     * 通过模板构造邮件内容，参数content将替换模板文件中的${content}标签。 
     */  
    private String getMailText(String type,SysUser sysUser) throws Exception {  
        // 通过指定模板名获取FreeMarker模板实例  
        SysUser user = sysUserMapper.selectByUserName(sysUser.getUsername()); 
        // FreeMarker通过Map传递动态数据  
        Map<String, String> map = new HashMap<String, String>();   
        map.put("username", user.getUsername()); // 注意动态数据的key和模板标签中指定的属性相匹配  
        map.put("shopUrl", Global.getConfig("shop.url")); 
        String templateName = "";
        if(Global.EMAIL_RESET.equals(type)){
        	templateName = "reset_email.ftl";
        }else{
        	templateName = "active_email.ftl";
        }
        map.put("activeCode", user.getActiveCode());  
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);   
       
      
          
        // 解析模板并替换动态数据，最终content将替换模板文件中的${content}标签。  
        String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);  
        return htmlText;  
    }  
}  